<template>
  <el-form
    ref="loginForm"
    :model="state.ruleForm"
    :rules="state.rules"
    @keydown.enter="handleSubmit"
    class="form-login"
    v-if="state.refresh"
  >
    <el-form-item prop="userName">
      <!--账号密码登录-->
      <el-input
        size="large"
        v-show="activeTab === 1"
        v-model="state.ruleForm.userName"
        placeholder="账号:admin"
      ></el-input>
      <!--短信登录-->
      <!-- <el-input
        size="large"
        v-show="activeTab === 2"
        v-model="state.form.phoneNumber"
        placeholder="手机号"
      >
        <template #prefix> 中国 +86<i class="el-input__icon el-icon-search"></i> </template>
      </el-input> -->
    </el-form-item>
    <el-form-item prop="password">
      <!--账号密码登录-->
      <el-input
        size="large"
        v-show="activeTab === 1"
        type="password"
        v-model="state.ruleForm.passWord"
        placeholder="密码:yl200815"
      ></el-input>
      <!--短信登录-->
      <!-- <el-input
        size="large"
        v-show="activeTab === 2"
        v-model="state.form.code"
        placeholder="请输入短信验证码"
      >
        <template #suffix>
          <span v-show="activeTab === 2" class="slot-icon">
            <a
              href="javascript:void(0)"
              @click="onGetCode"
              :style="{ color: state.time <= 0 ? '' : '#ccc' }"
            >
              <template v-if="state.time > 0">
                获取验证码
                <span>({{ state.time }}s)</span>
              </template>
              <template v-else> 重新获取 </template>
            </a>
          </span>
        </template>
      </el-input> -->
    </el-form-item>
    <el-form-item>
      <el-button class="submit" size="large" @click.stop="handleSubmit" color="#6C52EA" long
        >{{ activeTab === 2 ? '登录 / 注册' : '登录' }}
      </el-button>
    </el-form-item>
  </el-form>
</template>
<script setup>
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { dataInterfaces } from '@/apis/login/login'
import { getUserInfos } from '@/apis/login/login'
import { getUserList } from '@/apis/system/userInfo'
import { getRoleList } from '@/apis/jurisdiction/role'
import { useRouter } from 'vue-router'

import { userStore } from '@/store/user'
const $store = userStore()

import { getCurrentInstance } from 'vue'
import md5 from 'js-md5' //导入
const { proxy } = getCurrentInstance()
proxy.$md5 = md5 //md5转换为vue原型



const props = defineProps({
  userNameRules: {
    type: Array,
    default: () => {
      return [
        { required: true, message: '账号不能为空', trigger: 'blur' },
        { required: true, message: '手机号不能为空', trigger: 'blur' }
      ]
    }
  },
  passwordRules: {
    type: Array,
    default: () => {
      return [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    }
  },
  activeTab: {
    type: Number,
    required: true,
    default: null
  }
})
const emits = defineEmits(['on-success-valid'])
const state = reactive({
  ruleForm: {
    userName: '',
    passWord: ''
  },
  rules: {
    userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    passWord: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  },
  //   form: {
  //     // 用户名
  //     userName: '',
  //     // 手机号
  //     phoneNumber: '',
  //     // 密码
  //     password: '',
  //     // 验证码
  //     code: ''
  //   },
  // 手机号正则
  phoneReg: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
  // 结束时间戳
  endTime: 0,
  // 倒计时（重发）
  countDown: 0,
  // 计时器对象
  interval: null,
  hasCode: false,
  // 倒计时
  time: 0,
  code: '',
  btnTitle: '登录',
  btnType: 'primary',
  btnStatus: false,
  hasCode: false,
  btnWidthType: true,
  hasCode: false,
  //切换刷新
  refresh: true,
  // 验证码获取状态 0 从未获取 1 获取中 2  已获取已过期(重新获取) 3 已获取未过期(倒计时)
  codeStatus: 0
})

/**
 * @desc: 获取验证码
 * 验证码获取状态 0 从未获取 1 获取中 2  已获取已过期(重新获取) 3 已获取未过期(倒计时)
 */
const onGetCode = () => {
  if (state.time <= 0) {
    if (!state.form.phoneNumber || !state.phoneReg.test(state.form.phoneNumber)) {
      ElMessage.error('请输入正确格式的手机号码!')
      return
    }
    state.time = 60
    countDown()
    dataInterfaces({
      __method_name__: 'globalFunctionCall',
      typeName: 'LoginFuncClass',
      type: 'behavior',
      funcName: 'SendLoginSms',
      payload: {
        phone: state.form.phoneNumber
      }
    }).then((res) => {
      if (res.code == 200) {
        ElMessage.success('发送成功!')
        state.hasCode = true
      }
    })
  }
}
/**
 * @desc: 倒计时
 */
const countDown = () => {
  if (state.time > 0) {
    state.interval = setInterval(() => {
      state.time = state.time - 1
      if (state.time < 1) {
        clearInterval(state.interval)
        state.hasCode = false
      }
    }, 1000)
  } else {
    clearInterval(this.interval)
    state.hasCode = false
  }
}
/**
 * @desc: 登录
 */
const router = useRouter()
const loginForm = ref()
const userInfo = ref()
const handleSubmit = () => {
  loginForm.value.validate((valid) => {
    if (valid) {
      getUserInfos(state.ruleForm.userName, proxy.$md5(state.ruleForm.passWord)).then((res) => {
        if (!res.errorMsg) {
          userInfo.value = res
          localStorage.setItem('token', res.token)
          ElMessage({ type: 'success', message: '登录成功' })
          getUserData(userInfo.value.id)
          localStorage.setItem('user', JSON.stringify(res))
          router.push('/home/home-page')
        } else {
          ElMessage.success('用户或密码错误！')
        }
      })
    }
  })
}

/**
 * @desc:获取人员对应权限
 * @param {Array} search 搜索
 */
const getUserData = (id) => {
  getUserList({
    user_id: id
  })
    .then((res) => {
      if (!res) return
      roleId.value = res[0].role_id
      getRoleData()
    })
    .catch((res) => {
      ElMessage('服务器内部错误')
    })
    .finally(() => {
    })
}

/**
 * @desc: 获取对应角色表
 * @return {*}
 */
const roleId = ref('')
const getRoleData = () => {
  getRoleList({
    role_id: roleId.value
  }).then((res) => {
    if (!res) return
    let arr = []
    res?.roleList[0]?.role_menu?.map((item) => {
      if (!!item.permission_code) {
        arr.push(item.permission_code)
      }
    })
    $store.userRoles = arr
  })
}
</script>
<style scoped lang="less">
.slot-icon {
  padding-left: 10px;
  color: #a1a5ad;
  font-size: 14px;
  border-left: 1px solid #dcdee2;
  a {
    color: #0076ff;
  }
}
@media (max-width: 1366px) {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
<style lang="less">
.form-login {
  overflow: hidden;
  .ivu-input-group-prepend,
  .ivu-input-group-append {
    background-color: #fff;
  }
  .submit {
    width: 100%;
    height: 40px !important;
    color: #fff;
    font-weight: bold;
    letter-spacing: 8px;
    border-radius: 10px;
    cursor: pointer;
    /* 动画过渡 */
    transition: 0.5s;
  }
  input::-webkit-input-placeholder {
    /* placeholder颜色  */
    color: #a1a5ad;
    /* placeholder字体大小  */
    font-size: 14px;
  }
}
</style>
